package com.canyou.integration.authenticator;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.canyou.integration.IntegrationAuthentication;
import com.canyou.integration.IntegrationClientConstant;
import com.canyou.system.model.User;
import com.canyou.system.service.UserService;
import me.chanjar.weixin.common.error.WxErrorException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

/**
 * 小程序集成认证
 *
 * @author cgz
 * @date 2019-5-10
 **/
@Service
public class WxAppAuthenticator implements IntegrationAuthenticator {

    @Autowired
    private UserService userService;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private WxMaService wxMaService;

    @Override
    public User authenticate(IntegrationAuthentication integrationAuthentication) {
        WxMaJscode2SessionResult session = null;
        //实际值是微信小程序返回的code
        String code = integrationAuthentication.getAuthParameter("password");
        if (StrUtil.isBlank(code)) {
            throw new InternalAuthenticationServiceException("请检查password参数是否为空。");
        }
        try {
            session = wxMaService.getUserService().getSessionInfo(code);
        } catch (WxErrorException e) {
            throw new InternalAuthenticationServiceException("获取微信小程序用户信息失败", e);
        }
        String openId = session.getOpenid();
        User user = userService.getOne(Wrappers.<User>lambdaQuery().eq(User::getOpenid, openId));
        if (user == null) {
            user = new User();
            user.setOpenid(openId);
            user.setUsername(openId);
            user.setStatus(1);
            userService.save(user);
        }
        user.setPassword(passwordEncoder.encode(code));
        return user;
    }

    @Override
    public void prepare(IntegrationAuthentication integrationAuthentication) {

    }

    @Override
    public boolean support(IntegrationAuthentication integrationAuthentication) {
        return IntegrationClientConstant.AUTH_TYPE_WXAPP.equals(integrationAuthentication.getAuthType());
    }

    @Override
    public void complete(IntegrationAuthentication integrationAuthentication) {

    }
}
